package com.ruixun.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Redis服务类
 * @author ruixun
 */
@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 存储token
     */
    public void storeToken(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    /**
     * 获取token
     */
    public Object getToken(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除token
     */
    public void deleteToken(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 检查token是否存在
     */
    public boolean hasToken(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 设置token过期时间
     */
    public void setTokenExpiration(String key, long timeout, TimeUnit unit) {
        redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获取token剩余过期时间
     */
    public long getTokenExpiration(String key) {
        Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
        return expire != null ? expire : -1;
    }
}